import { drawFillRect, drawFillText } from '../utils/draw.js';
import NeuralNetwork from '../utils/nn.js';
import { getDistanceBetweenCircles } from '../utils/tool.js';
import Player from './Player.js';

const thinkResultObj = {
    0: '上',
    1: '下',
    2: '左',
    3: '右',
    4: '停',
};

/** AI类 */
export default class AI extends Player {
    constructor(ctx, x, y, brain) {
        super(ctx, x, y, null, null, 16);

        this.thinkResult = 0; // 执行的动作
        this.fitness = 0; // 适应度

        // 添加人工智能
        if (brain) {
            this.brain = brain.copy();
        } else {
            this.brain = new NeuralNetwork(4, 8, 5);
        }
    }

    dispose() {
        this.brain.dispose();
    }

    mutate() {
        this.brain.mutate(0.1);
    }

    moveUp() {
        this.moveY(false);
    }

    moveDown() {
        this.moveY(true);
    }

    moveLeft() {
        this.moveX(false);
    }

    moveRight() {
        this.moveX(true);
    }
    moveStop() {
        this.stopMove();
    }

    /** 更新神经网络策略 */
    update() {
        let inputs = [];
        // 输入为玩家到六个石头中最近的石头之间的距离和五个星星中最近的星星之间的距离以及自身的x,y坐标
        const _this = this;
        let stockDistance = window.GameData.stockArr.map(stock => getDistanceBetweenCircles(stock, _this) / window.GameData.canvas.width);
        let stockDistanceSort = stockDistance.sort((a, b) => a - b);
        inputs.push(stockDistanceSort[0]);

        let starDistance = window.GameData.starArr.map(star => getDistanceBetweenCircles(star, _this) / window.GameData.canvas.width);
        let starDistanceSort = starDistance.sort((a, b) => a - b);
        inputs.push(starDistanceSort[0]);

        inputs.push(this.x / window.GameData.canvas.width, this.y / window.GameData.canvas.height);

        let output = this.brain.predict(inputs);

        // 输出是一个长度为4的数字数字，我们去最大值所在的下标来表示最可能的预测结果
        let maxValue = Math.max(...output); // 找到数组中的最大值
        this.thinkResult = output.indexOf(maxValue); // 找到最大值的下标
        // console.log(' this.thinkResult-->', this.thinkResult);

        if (this.thinkResult === 0) this.moveUp();
        if (this.thinkResult === 1) this.moveDown();
        if (this.thinkResult === 2) this.moveLeft();
        if (this.thinkResult === 3) this.moveRight();
        if (this.thinkResult === 4) this.moveStop();

        super.update();
    }

    draw() {
        // 绘制当前玩家的分数
        super.draw();
        // drawFillText(this.ctx, this.x - this.radius / 3, this.y + this.radius / 2, this.score, 'red', 20);
        drawFillText(this.ctx, this.x - this.radius / 2, this.y + this.radius / 2, thinkResultObj[this.thinkResult], 'red', 20);
    }
}
